import { validateNull } from '@/libs/validate.js'



/**
 * 会话存储
 * @param key
 * @param value
 */
export function setSessionStore(key, obj) {
    return window.sessionStorage.setItem(key, JSON.stringify(obj))
}

/**
 * 获取会话存储
 * @param key
 * @returns {string | null}
 */
export function getSessionStore(key) {
    return window.sessionStorage.getItem(key)
}

/**
 * 删除会话存储
 * @param key
 */
export function removeSessionStore(key) {
    window.sessionStorage.removeItem(key)
}

/**
 * 清除所有会话存储
 */
export function clearSessionStore() {
    window.sessionStorage.clear()
}

/**
 * 本地存储
 * @param key
 * @param obj
 */
export function setLocalStore(key, obj) {
    return window.localStorage.setItem(key, JSON.stringify(obj))
};

/**
 * 获取本地存储
 * @param key
 * @returns {string | null}
 */
export function getLocalStore(key) {
    return window.localStorage.getItem(key)
};

/**
 * 删除本地存储
 * @param key
 */
export function removeLocalStore(key) {
    window.localStorage.removeItem(key)
};

/**
 * 清除所有本地存储
 */
export function clearLocalStore() {
    window.localStorage.clear()
};

/**
 * 存储localStorage
 */
export const setStore = (params) => {
    let { name, content, type, datetime } = params;
    let obj = {
        dataType: typeof (content),
        content: content,
        type: type,
        datetime: new Date().getTime()
    }
    if (type) window.sessionStorage.setItem(name, JSON.stringify(obj));
    else window.localStorage.setItem(name, JSON.stringify(obj));
};

/**
 * 获取localStorage
 */
export const getStore = (params) => {
    let { name, type } = params;
    let obj = {}, content;
    obj = window.localStorage.getItem(name);
    if (validateNull(obj)) obj = window.sessionStorage.getItem(name);
    if (validateNull(obj)) return;
    obj = JSON.parse(obj);
    if (obj.dataType == 'string') {
        content = obj.content;
    } else if (obj.dataType == 'number') {
        content = Number(obj.content);
    } else if (obj.dataType == 'boolean') {
        content = eval(obj.content);
    } else if (obj.dataType == 'object') {
        content = obj.content;
    }
    return content;
};
/**
 * 删除localStorage
 */
export const removeStore = params => {
    let { name } = params;
    window.localStorage.removeItem(name);
    window.sessionStorage.removeItem(name);
}